﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Configuration;
using eCitizen.eAlerts.Classes;

namespace eCitizen.eAlerts.Utilities
{
    public class SftpConnectionManager
    {
        private static List<SftpConfiguration> _sftpConfigurations;
        public List<SftpConfiguration> SftpConfigurations { get { return _sftpConfigurations; } }
        private string configurationFileUrl;
        public SftpConnectionManager()
        {
            configurationFileUrl = ConfigurationManager.AppSettings["sFTPConfigurationFile"];
            if (_sftpConfigurations == null) LoadConfigurations();
        }


        // Temporarily using Local IO, change it to sFTP Later
        public List<ServiceRequest> GeteAlertRequestFiles(SftpConfiguration fileConfiguration)
        {

            List<ServiceRequest> filePairs = new List<ServiceRequest>();
            // 1. Get all files in the Agency Inbox {Only .DAT files}
            string directoryUrl = string.Format("{0}\\{1}\\{2}\\{3}",fileConfiguration.RootDirectoryUrl,fileConfiguration.Agency,fileConfiguration.Service,fileConfiguration.InboxUrl);

            if (Directory.Exists(directoryUrl))
            {
                List<string> fileEntries = Directory.GetFiles(directoryUrl, "*.DAT").ToList();

                // 2. Iterate the list of the files
                if (fileEntries != null && fileEntries.Count > 0)
                {
                    foreach (string requestFile in fileEntries)
                    {
                        string requestFileName = Path.GetFileNameWithoutExtension(requestFile);
                        string requestFilePath = Path.GetDirectoryName(requestFile);
                        string checkSumFile = string.Format("{0}\\{1}.SUM", requestFilePath, requestFileName);

                        if (File.Exists(requestFile) && File.Exists(checkSumFile))
                        {
                            ServiceRequest currentRequest = new ServiceRequest();

                            // Get the request file 

                            currentRequest.RequestFileName = Path.GetFileName(requestFile);
                            currentRequest.RequestFileFullPath = requestFile;
                            currentRequest.RequestFile = new StreamReader(requestFile);
                            // Get the check sum file
                            currentRequest.ChecksumFileName = Path.GetFileName(checkSumFile);
                            currentRequest.ChecksumFileFullPath = checkSumFile;
                            currentRequest.ChecksumFile = new StreamReader(checkSumFile);


                            ServiceInfo currentService = new ServiceInfo();
                            currentService.ProcessFileName = Path.GetFileName(requestFile);
                            currentService.ServiceId = fileConfiguration.Service;
                            currentService.ServiceStartDatetime = System.DateTime.Now;
                            currentService.CurrentServiceType = ServiceType.SendAlertService;

                            currentRequest.CurrentServiceInfo = currentService;

                            filePairs.Add(currentRequest);
                        }
                        else
                        {
                            // Cannot find the full file pair
                            ErrorLogManager errorLogManager = new ErrorLogManager();
                            errorLogManager.CreateErrorLogfile(fileConfiguration, ErrorMessageConstants.SendAlertService_ChecksumFileNotFound);
                        }

                    }

                }
                else
                {
                    // No files found to process
                }
            }
            return filePairs;
        }
        
        public List<ServiceRequest> GetReportFiles(SftpConfiguration fileConfiguration)
        {
            List<ServiceRequest> files = new List<ServiceRequest>();

            string directory = string.Format("{0}\\{1}\\{2}\\{3}", fileConfiguration.SmsConfiguration.SmsRootDirectoryUrl, fileConfiguration.SmsConfiguration.Agency, fileConfiguration.SmsConfiguration.Service, fileConfiguration.SmsConfiguration.OutboxUrl);
            System.DateTime reportDate = System.DateTime.Now.AddDays(-1);
            string fileName = string.Format("{0}.rpt", reportDate.ToString(ServiceConstants.DateFormats.YYYYMMDD));
            string fullFilePath = string.Format("{0}\\{1}",directory,fileName);


            if (Directory.Exists(directory) && File.Exists(fullFilePath))
            {
                ServiceRequest currentRequest = new ServiceRequest();

                currentRequest.RequestFileName = fileName;
                currentRequest.RequestFileFullPath = fullFilePath;
                currentRequest.RequestFile = new StreamReader(fullFilePath);

                ServiceInfo currentService = new ServiceInfo();
                currentService.ProcessFileName = fileName;
                currentService.ServiceId = fileConfiguration.Service;
                currentService.ServiceStartDatetime = System.DateTime.Now;
                currentService.CurrentServiceType = ServiceType.SendReportService;

                currentRequest.CurrentServiceInfo = currentService;

                files.Add(currentRequest);
            }

            return files;
        }

        // This method will load all of the Agency folders as configurations
        private void LoadConfigurations()
        {
            _sftpConfigurations = new List<SftpConfiguration>();

            FileStream stream = new FileStream(configurationFileUrl, FileMode.Open);
            XmlDocument configDocument = new XmlDocument();
            configDocument.Load(stream);

            XmlNodeList configList = configDocument.SelectNodes("/connections/sftpConnection");

            foreach (XmlNode config in configList) 
            {

                // 1. Read the main sFTP configruation : the location of eAlertService
                SftpConfiguration sftpConfiguration = new SftpConfiguration();
                sftpConfiguration.RootDirectoryUrl = ((XmlElement)config).GetElementsByTagName("RootDirectoryUrl")[0].InnerText;
                sftpConfiguration.Agency = ((XmlElement)config).GetElementsByTagName("Agency")[0].InnerText;
                sftpConfiguration.Service = ((XmlElement)config).GetElementsByTagName("Service")[0].InnerText;
                sftpConfiguration.InboxUrl = ((XmlElement)config).GetElementsByTagName("InboxUrl")[0].InnerText;
                sftpConfiguration.OutboxUrl = ((XmlElement)config).GetElementsByTagName("OutboxUrl")[0].InnerText;

                // 2. Read Sms Service configuration : the location of OneSMSService if applicable
                XmlNodeList smsServiceConfigurationlist = config.SelectNodes("/connections/sftpConnection/OneSmsService");

                foreach (XmlNode smsConfig in smsServiceConfigurationlist)
                {
                    if (((XmlElement)smsConfig).GetElementsByTagName("Agency")[0].InnerText == sftpConfiguration.Agency && ((XmlElement)smsConfig).GetElementsByTagName("Service")[0].InnerText == sftpConfiguration.Service)
                    {
                        sftpConfiguration.SmsConfiguration.SmsRootDirectoryUrl = ((XmlElement)smsConfig).GetElementsByTagName("SMSRootDirectoryUrl")[0].InnerText;
                        sftpConfiguration.SmsConfiguration.Agency = ((XmlElement)smsConfig).GetElementsByTagName("Agency")[0].InnerText;
                        sftpConfiguration.SmsConfiguration.Service = ((XmlElement)smsConfig).GetElementsByTagName("Service")[0].InnerText;
                        sftpConfiguration.SmsConfiguration.InboxUrl = ((XmlElement)smsConfig).GetElementsByTagName("InboxUrl")[0].InnerText;
                        sftpConfiguration.SmsConfiguration.OutboxUrl = ((XmlElement)smsConfig).GetElementsByTagName("OutboxUrl")[0].InnerText;
                    }
                }
                _sftpConfigurations.Add(sftpConfiguration);
            }

        }



    }
}
